package com.cloud.message.service.impl;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.cloud.ding_talk.DingGrantUtils;
import com.cloud.ding_talk.vo.DingNotice;
import com.cloud.entity.SysNoticeUser;
import com.cloud.entity.SysProjectAuth;
import com.cloud.entity.SysUser;
import com.cloud.entity.vo.AuthParam;
import com.cloud.entity.vo.NoticeParam;
import com.cloud.enums.AuthMode;
import com.cloud.enums.NoticeMode;
import com.cloud.enums.ReadStatus;
import com.cloud.message.service.IMessageService;
import com.cloud.service.FeignSystemService;
import com.cloud.utils.StringUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements IMessageService {

    @Resource
    private FeignSystemService feignSystemService;

    @Autowired
    private EmailProperties emailProperties;

    /**
     * 指定用户发送邮件信息
     */
    @Override
    public List<SysNoticeUser> sendMailNotice(NoticeParam noticeParam) {
        List<SysNoticeUser> noticeUserList = new ArrayList<>();
        List<String> mailList = new ArrayList<>();
        for (Long userId : noticeParam.getUserIdList()) {
            noticeUserList.add(setNoticeUserInfo(noticeParam.getNoticeId(), userId));
            SysUser sysUser = feignSystemService.selectInUserInfo(userId).getData();
            if (StringUtils.isNotNull(sysUser) && StringUtils.isNotEmpty(sysUser.getEmail())) {
                mailList.add(sysUser.getEmail());
            }
        }
        if (mailList.size() > 0) {
            MailAccount account = new MailAccount();
            account.setHost(emailProperties.getHost());
            account.setPort(emailProperties.getPort());
            account.setFrom(emailProperties.getFromMail());
            account.setUser(emailProperties.getUserName());
            account.setPass(emailProperties.getPassword());
            account.setAuth(true);
            MailUtil.send(account, mailList, noticeParam.getTitle(), noticeParam.getContent(), false);
        }
        return noticeUserList;
    }

    /**
     * 指定用户发送浙政钉消息
     */
    @Override
    public List<SysNoticeUser> sendDingTalkNotice(NoticeParam noticeParam) {
        List<SysNoticeUser> noticeUserList = new ArrayList<>();
        for (Long userId : noticeParam.getUserIdList()) {
            noticeUserList.add(setNoticeUserInfo(noticeParam.getNoticeId(), userId));
        }
        // 根据系统账户ID获取浙政钉授权用户ID信息
        AuthParam authParam = new AuthParam();
        authParam.setAuthType(AuthMode.TALK_APP.getCode());
        if (ObjectUtils.isEmpty(noticeParam.getUserIdList())) {
            return noticeUserList;
        }
        String userIds = noticeParam.getUserIdList().stream()
                .map(String::valueOf).collect(Collectors.joining(","));
        authParam.setUserIds(userIds);
        List<String> accountIdList = feignSystemService.getUserAuthIds(authParam).getData();
        if (StringUtils.isNotNull(accountIdList)) {
            SysProjectAuth projectAuth = new SysProjectAuth();
            projectAuth.setSysCode(noticeParam.getSysCode());
            projectAuth.setAuthType(AuthMode.TALK_APP.getCode());
            projectAuth = feignSystemService.selectProjectAuth(projectAuth).getData();
            if (StringUtils.isNotNull(projectAuth) && StringUtils.isNotEmpty(projectAuth.getTenantId())) {
                // 发送浙政钉工作消息
                DingGrantUtils dingTalk = new DingGrantUtils(projectAuth.getDomainName(),
                        projectAuth.getAccessKey(), projectAuth.getSecretKey());
                for (String accountId : accountIdList) {
                    DingNotice notice = new DingNotice(projectAuth.getTenantId(), accountId,
                            noticeParam.getTitle(), noticeParam.getOuterId(), noticeParam.getContent());
                    dingTalk.dingTalkNotice(notice);
                }
            }
        }
        return noticeUserList;
    }

    /**
     * 设置发送消息与用户关联列表
     */
    @Override
    public List<SysNoticeUser> setNoticeUserList(NoticeParam noticeParam) {
        List<SysNoticeUser> noticeUserList = new ArrayList<>();
        for (Long userId : noticeParam.getUserIdList()) {
            noticeUserList.add(setNoticeUserInfo(noticeParam.getNoticeId(), userId));
        }
        return noticeUserList;
    }

    /**
     * 根据消息类型设置发送公告与用户关联
     */
    @Override
    public List<SysNoticeUser> setNoticeUserInfo(NoticeParam noticeParam) {
        List<SysNoticeUser> noticeUserList = null;
        if (NoticeMode.SYSTEM.getCode() == noticeParam.getSendType()) {
            noticeUserList = setNoticeUserList(noticeParam);
        }
        // 发送EMail邮件消息
        if (NoticeMode.EMAIL.getCode() == noticeParam.getSendType()) {
            noticeUserList = sendMailNotice(noticeParam);
        }
        // 发送浙政钉工作消息
        if (NoticeMode.DING_TALK_MSG.getCode() == noticeParam.getSendType()) {
            noticeUserList = sendDingTalkNotice(noticeParam);
        }
        return noticeUserList;
    }

    /**
     * 设置发送消息与用户关联对象
     */
    private SysNoticeUser setNoticeUserInfo(Long noticeId, Long userId) {
        SysNoticeUser noticeUser = new SysNoticeUser();
        noticeUser.setNoticeId(noticeId);
        noticeUser.setUserId(userId);
        noticeUser.setReadStatus(ReadStatus.UNREAD.getCode());
        return noticeUser;
    }

}
